Skip to content

feat: add rule to prevent comments after attributes #4101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 2.1.x
Choose a base branch
from

Conversation

calebdw
Copy link
Contributor

@calebdw calebdw commented Jul 17, 2025

Hello!

Motivation

I've had issues with developers adding the doc comment after attributes:

#[Foo]
/** @param array<int, string> $foo */
function bad(array $foo): void {...}

// should be

/** @param array<int, string> $foo */
#[Foo]
function good(array $foo): void {...}

The former is actually a bug---the doc comment is invisible to PHP-Parser and is not used: https://phpstan.org/r/987e775c-225b-4248-a772-e97367baf952

So I decided to try and create a rule to prevent these situations.

Implementation

Given that the comment is completely invisible to PHP-Parser, this becomes more difficult than simply comparing the starting line of the comment to the ending line of the attribute group.

Basically what I'm trying to do is find "holes" by comparing the last line of the last attribute group to the starting line of the next identifier (class, property, enum, etc. name). If there's a "hole" (the identifier does not start on the same or next line) then I report the error.

I'm open to suggestions for better class name / error identifier / error message.

CC: @staabm, would you mind taking a look at this?

Thanks!

@calebdw calebdw force-pushed the calebdw/push-lkvqovwystuw branch from b792b97 to 2825633 Compare July 17, 2025 04:34
@ondrejmirtes
Copy link
Member

This bug has an issue: phpstan/phpstan#4633

I don't think we should add rules about bugs, we shoud fix those bugs.

I think for a long time this one could be fixed with an AST visitor.

Similarly to the visitor which adds linesToIgnore, this one could look at lexer tokens and add comments between attributes and code to Node comments.

@calebdw
Copy link
Contributor Author

calebdw commented Jul 17, 2025

Even if this "bug" is fixed by being able to parse the comments I would still want a rule to enforce that comments come before attributes (but that can be more of a strict/opinionated rule at that point). To borrow an analogy from chemistry, the attribute is an actual language construct and should bind more closely with the node than a doc comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants